#include "factory.h"

//为每个子线程初始化一个链接
int mysql_connect(MYSQL **conn,int port)
{
    MYSQL_RES *res;//结果操作指针
    MYSQL_ROW row;//一行的数据是存在row中间
    const char* server="localhost";//地址
    const char *user="root";
    const char* passwd="123";
    const char *database="newdisk";//数据库名称
    *conn=mysql_init(NULL);//初始化
    if(!mysql_real_connect(*conn,server,user,passwd,database,port,NULL,0))
    {
        printf("error connecting todatabase:%s\n",mysql_error(*conn));
        return -1;
    }else{
#ifdef DEBUG
        printf("connected...\n");
#endif
        return 0;
    }
}

//验证用户名是否存在
int check_username_exist(MYSQL *conn,char *username)
{
    unsigned int t;
    MYSQL_RES *res;
    MYSQL_ROW row;
    int return_flag;
    char *p="selct user_name from users where user_name='";
    char query[300]={0};
    //将p与username拼接后存入query
    sprintf(query,"%s%s'",p,username);
#ifdef DEBUG
    puts(query);
#endif
    t=mysql_query(conn,query);//执行sql语句
    if(t)
    {
        printf("Error making query:%s\n",mysql_error(conn));//sql语法出错
    }else{
        printf("Query made...\n");
        res=mysql_use_result(conn);//获取结果
        if(res)
        {
            row=mysql_fetch_row(res);
            if(NULL==row)
            {
                return_flag=0;//没有查到结果
            }else{
                return_flag=1;//查到结果
            }
        }
        mysql_free_result(res);        
    }
    return return_flag;
}

//把用户名和密码插入数据库
uint64_t insert_new_user(MYSQL *conn,username_passwd_t *p)
{
    unsigned int t;
    char salt[20]="$6$";
    generate_random_string(salt);//拼接颜值

    struct crypt_data cr_data;
    crypt_r(p->passwd,salt,&cr_data);//得到密文

    char *psql="insert into users values(0,'";
    char query[1000]={0};
    sprintf(query,"%s%s','%s','%s')",psql,p->user_name,salt,cr_data.output);
#ifdef DEBUG
    puts(query);
#endif
    t=mysql_query(conn,query);//执行sql
    if (t)
    {
        printf("Error making query:%s\n",mysql_error(conn));
        return 0;        
    }else{
        return mysql_affected_rows(conn);
    }    
}

//验证用户名和密码是否存在
int check_login(MYSQL *conn,username_passwd_t *p)
{
    unsigned int t;
    int login_flag;
    MYSQL_RES *res;
    MYSQL_ROW row;
    struct crypt_data cr_data;

    char *psql="SELECT salt,ciphertext FROM users WHERE user_name='";
    char query[1000]={0};
    sprintf(query,"%s%s'",psql,p->user_name);
    puts(query);
    t=mysql_query(conn,query);
    if(t)
    {
        printf("Error making query:%s\n",mysql_error(conn));
    }else{
        printf("Query made...\n");
        res=mysql_use_result(conn);
        if(res)
        {
            row=mysql_fetch_row(res);
            if(row)
            {
                crypt_r(p->passwd,row[0],&cr_data);
                if(!strcmp(cr_data.output,row[1]))
                {
                    login_flag=1;//登陆成功
                }else{
                    login_flag=0;//（有）用户名或密码错误
                }
            }else{
                login_flag=0;//用户名不存在
            }
        }
        mysql_free_result(res);        
    }
    return login_flag;
}

int get_user_id(MYSQL *conn,char *username)
{
    unsigned int t;
    MYSQL_RES *res;
    MYSQL_ROW row;
    int return_id;
    char *p="select user_id from users where user_name='";
    char query[300]={0};
    sprintf(query,"%s%s'",p,username);
    puts(query);
    t=mysql_query(conn,query);
    if(t)
    {
        printf("Error making query:%s\n",mysql_error(conn));//sql的语法出错
    }else{
		printf("Query made...\n");
		res=mysql_use_result(conn);//获取结果
		if(res)
		{
			row=mysql_fetch_row(res);
			if(NULL==row)
			{
				return_id=0;//没查到结果
			}
			else{
				return_id=atoi(row[0]);//查到结果
			}
		}
		mysql_free_result(res);
	}
    return return_id;
}

int check_dir_isexist(MYSQL* conn,int user_id,int path_id,char* dir_name)
{
	unsigned int t;
    MYSQL_RES *res;//结果操作指针
	MYSQL_ROW row;//一行的数据是存在row中间
    int return_id;
    char *p="select count(*) from file_system where user_id=";
    char query[300]={0};
    sprintf(query,"%s%d and pre_id=%d and file_name='%s'",p,user_id,path_id,dir_name);
    puts(query);
	t=mysql_query(conn,query);//执行sql语句
	if(t)
	{
		printf("Error making query:%s\n",mysql_error(conn));//sql的语法出错
	}else{
		printf("Query made...\n");
		res=mysql_use_result(conn);//获取结果
		if(res)
		{
			row=mysql_fetch_row(res);
			if(NULL==row)
			{
				return_id=0;//没查到结果
			}
			else{
				return_id=atoi(row[0]);//查到结果
			}
		}
		mysql_free_result(res);
	}
    return return_id;
}

uint64_t creat_dir(MYSQL* conn,int user_id,int path_id,char* dir_name)
{
	unsigned int t;

	char *psql="INSERT INTO file_system (pre_id, file_name, user_id, file_type, file_size) VALUES (";
	char query[1000]={0};
	sprintf(query,"%s%d,'%s',%d, 'd', 4096)",psql,path_id,dir_name,user_id);
    puts(query);
	t=mysql_query(conn,query);//执行sql
	if(t)
	{
		printf("Error making query:%s\n",mysql_error(conn));
		return 0;
	}else{
		return mysql_affected_rows(conn);
	}
}


int check_cd_dir_isexist(MYSQL* conn,int user_id,int path_id,char* dir_name)
{
	unsigned int t;
    MYSQL_RES *res;//结果操作指针
	MYSQL_ROW row;//一行的数据是存在row中间
    int ret_path_id;
    char *p="select path_id from file_system where user_id=";
    char query[300]={0};
    sprintf(query,"%s%d and pre_id=%d and file_name='%s' and file_type='d'",p,user_id,path_id,dir_name);
    puts(query);
	t=mysql_query(conn,query);//执行sql语句
	if(t)
	{
		printf("Error making query:%s\n",mysql_error(conn));//sql的语法出错
	}else{
		printf("Query made...\n");
		res=mysql_use_result(conn);//获取结果
		if(res)
		{
			row=mysql_fetch_row(res);
			if(NULL==row)
			{
				ret_path_id=0;//没查到结果
			}
			else{
				ret_path_id=atoi(row[0]);//查到结果
			}
		}
		mysql_free_result(res);
	}
    return ret_path_id;
}


int get_pre_id(MYSQL* conn,int path_id)
{
	unsigned int t;
    MYSQL_RES *res;//结果操作指针
	MYSQL_ROW row;//一行的数据是存在row中间
    int ret_pre_id;
    char *p="select pre_id from file_system where path_id=";
    char query[300]={0};
    sprintf(query,"%s%d",p,path_id);
    puts(query);
	t=mysql_query(conn,query);//执行sql语句
	if(t)
	{
		printf("Error making query:%s\n",mysql_error(conn));//sql的语法出错
	}else{
		printf("Query made...\n");
		res=mysql_use_result(conn);//获取结果
		if(res)
		{
			row=mysql_fetch_row(res);
			if(NULL==row)
			{
				ret_pre_id=0;//没查到结果
			}
			else{
				ret_pre_id=atoi(row[0]);//查到结果
			}
		}
		mysql_free_result(res);
	}
    return ret_pre_id;
}

//查询一行，发送一行
void send_file_info(task_t* pnew)
{
	train_t train;
	unsigned int t;
	MYSQL_RES *res;//结果操作指针
	MYSQL_ROW row;//一行的数据是存在row中间
	char *p="select file_type,file_name,file_size from file_system where pre_id=";
    char query[300]={0};
    sprintf(query,"%s%d",p,pnew->path_id);
	t=mysql_query(pnew->conn,query);//执行sql语句
	if(t)
	{
		printf("Error making query:%s\n",mysql_error(pnew->conn));//sql的语法出错
	}else{
		printf("Query made...\n");
		res=mysql_use_result(pnew->conn);//获取结果
		if(res)
		{
			while((row=mysql_fetch_row(res))!=NULL)
			{	
				bzero(&train,sizeof(train_t));
				sprintf(train.buf,"%5s%15s%10s",row[0],row[1],row[2]);
				train.size=strlen(train.buf);
				send(pnew->new_fd,&train,4+train.size,0);
			}
			int end_flag=0;
			send(pnew->new_fd,&end_flag,4,0);//代表发送结束了
		}else{
			printf("Don't find data\n");
		}
		mysql_free_result(res);
	}
}

int rm_file_emptydir(task_t *pnew,char* rm_file_name)
{
	unsigned int t;
    MYSQL_RES *res;//结果操作指针
	MYSQL_ROW row;//一行的数据是存在row中间
    int rm_flag;
    char *p="select count(*) from file_system where pre_id=(select path_id from file_system where pre_id=";
    char query[300]={0};
    sprintf(query,"%s%d and file_name='%s')",p,pnew->path_id,rm_file_name);
    puts(query);
	t=mysql_query(pnew->conn,query);//执行sql语句
	if(t)
	{
		printf("Error making query:%s\n",mysql_error(pnew->conn));//sql的语法出错
	}else{
		printf("Query made...\n");
		res=mysql_use_result(pnew->conn);//获取结果
		if(res)
		{
			row=mysql_fetch_row(res);
			if(NULL==row)
			{
				rm_flag=0;//没查到结果
			}
			else{
				rm_flag=atoi(row[0]);//查到结果
			}
		}
		mysql_free_result(res);
	}
	//判断删除的是否是普通文件类型
	char md5_str[50]={0};
	p="select file_type,md5 from file_system where pre_id=";
    bzero(query,sizeof(query));
    sprintf(query,"%s%d and file_name='%s'",p,pnew->path_id,rm_file_name);
    puts(query);
	t=mysql_query(pnew->conn,query);//执行sql语句
	if(t)
	{
		printf("Error making query:%s\n",mysql_error(pnew->conn));//sql的语法出错
	}else{
		res=mysql_use_result(pnew->conn);//获取结果
		if(res)
		{
			row=mysql_fetch_row(res);
			if(NULL==row)
			{
				//如果用户输入的名字不对，啥都不错
			}
			else{
				if(row[0][0]=='f')//是普通文件
				{
					strcpy(md5_str,row[1]);
				}
			}
		}
		mysql_free_result(res);
	}
	//删除
	if(!rm_flag)
	{
		p="delete from file_system where pre_id=";
    	bzero(query,sizeof(query));
    	sprintf(query,"%s%d and file_name='%s'",p,pnew->path_id,rm_file_name);
		t=mysql_query(pnew->conn,query);
		if(t)
		{
			printf("Error making query:%s\n",mysql_error(pnew->conn));
		}else{
			printf("delete success,delete row=%ld\n",(long)mysql_affected_rows(pnew->conn));
		}
	}
	//是普通文件，就需要file_md5sum的引用计数减1
	if(md5_str[0])
	{
		p="update file_md5sum set reference_count=reference_count-1 where md5='";
		bzero(query,sizeof(query));
		sprintf(query,"%s%s'",p,md5_str);
		puts(query);
		t=mysql_query(pnew->conn,query);//执行sql
		if(t)
		{
			printf("Error making query:%s\n",mysql_error(pnew->conn));
		}
	}
	return !rm_flag;
}


uint64_t  check_file_md5_exist(task_t* pnew,char* md5_str)
{
	unsigned int t;

	char *psql="update file_md5sum set reference_count=reference_count+1 where md5='";
	char query[1000]={0};
	sprintf(query,"%s%s'",psql,md5_str);
    puts(query);
	t=mysql_query(pnew->conn,query);//执行sql
	if(t)
	{
		printf("Error making query:%s\n",mysql_error(pnew->conn));
		return 0;
	}else{
		return mysql_affected_rows(pnew->conn);//存在，这个值是1，不存在这个是0
	}
}


uint64_t creat_file(MYSQL* conn,int user_id,int path_id,char* file_name,char* md5_str)
{
	unsigned int t;

	char *psql="INSERT INTO file_system (pre_id, file_name, user_id, file_type,md5, file_size) VALUES (";
	char query[1000]={0};
	sprintf(query,"%s%d,'%s',%d, 'f','%s', (select file_size from file_md5sum where md5='%s'))",psql,path_id,file_name,user_id,md5_str,md5_str);
    puts(query);
	t=mysql_query(conn,query);//执行sql
	if(t)
	{
		printf("Error making query:%s\n",mysql_error(conn));
		return 0;
	}else{
		return mysql_affected_rows(conn);
	}
}

uint64_t creat_file_md5(MYSQL* conn,char* md5_str,off_t file_size)
{
	unsigned int t;

	char *psql="insert into file_md5sum VALUES(";
	char query[1000]={0};
	sprintf(query,"%s'%s',1,%ld)",psql,md5_str,file_size);
    puts(query);
	t=mysql_query(conn,query);//执行sql
	if(t)
	{
		printf("Error making query:%s\n",mysql_error(conn));
		return 0;
	}else{
		return mysql_affected_rows(conn);
	}
}

void get_md5_and_file_size(task_t* pnew,char* md5_str,off_t* file_size,char* file_name)
{
	unsigned int t;
	MYSQL_RES *res;//结果操作指针
	MYSQL_ROW row;//一行的数据是存在row中间
	char *p="select md5,file_size from file_system where pre_id=";
    char query[300]={0};
    sprintf(query,"%s%d and file_name='%s'",p,pnew->path_id,file_name);
	t=mysql_query(pnew->conn,query);//执行sql语句
	if(t)
	{
		printf("Error making query:%s\n",mysql_error(pnew->conn));//sql的语法出错
	}else{
		res=mysql_use_result(pnew->conn);//获取结果
		if(res)
		{
			row=mysql_fetch_row(res);
			strcpy(md5_str,row[0]);
			*file_size=atol(row[1]);
		}else{
			printf("Don't find data\n");
		}
		mysql_free_result(res);
	}
}